'use client'
import React, {useEffect, useRef, useState} from "react";
import {User} from "@/app/lib/user";
import {getFetch, postFetch,} from "@/app/lib/HttpProtocol";
import {
	Button,
	Drawer, message,
	Space,
	Table,
	TableProps,
} from "antd";
import {Security} from "@/app/lib/security";
import WorkEditModal from "@/app/home/system/user/WorkEditModal";
import WorkAddModal from "@/app/home/system/user/WorkAddModal";
import WorkDeleteModal from "@/app/home/system/user/WorkDeleteModal";
import WorkSetRolesModal from "@/app/home/system/user/WorkSetRolesModal";

class Work{
	id?:string;
	positionId?:string;
	positionName?:string;
	userid?:string;
	positionLevel?:number;
	positionType?:string;
	primary?:boolean;
	corpId?:string;
	corpName?:string;
	depts?:any[];
	roles?:any[];
}

const styleSize = "small"

const apis = {
	worksApi:'/user/workWithRoles/list',
	workAddApi:'/user/work/add',
	workUpdateApi:'/user/work/update',
	workDeleteApi:'/user/work/delete',
	workSetRoles:'/user/work/setRoles',
	corpListApi:'/corp/list/available',
	listRoleGroupsApi:'/role/list/groupByApp'
}

async function loadWorkPage(userid:string|null){
	return await getFetch(apis.worksApi,{userid:userid}).then(works => {
		return works;
	})
}

function addKey(works:Work[],user:User){
	return works.map(w => {
		Object.assign(w,{key:w.id,nickname:user.nickname});
		return w;
	})
}

// @ts-ignore
function getColumns(onEdit,onDelete,onSetRoles):TableProps<User>['columns']{
	return [
		{
			title:'公司',
			dataIndex:'corpName',
			key:'corpName',
		},
		{
			title:'职位',
			dataIndex:'positionName',
			key:'positionName',
		},{
			title:'类型',
			dataIndex:'positionType',
			key:'positionType',
		},{
			title:'职级',
			dataIndex:'positionLevel',
			key:'positionLevel',
		},{
			title:'主要',
			key:'primary',
			dataIndex:'primary',
			render:(primary) => primary ? '是' : '否'
		},{
			title:'角色',
			key:'roles',
			dataIndex:'roles',
			render:(roles) => {
				let roleNames:String = '';
				// @ts-ignore
				roles.forEach(r => {
					roleNames += r.name;
				})
				return roleNames;
			}
		},{
			title:'操作',
			key:'action',
			render:(_,work:Work) =>(
				<Space size="middle">
					<Security perm={apis.workDeleteApi}><Button size={styleSize} type="primary" onClick={() => onDelete(work)}>删除</Button></Security>
					<Security perm={apis.workUpdateApi}><Button size={styleSize} type="primary" onClick={() => onEdit(work)}>编辑</Button></Security>
					<Security perm={apis.workSetRoles}><Button size={styleSize} type="primary" onClick={() => onSetRoles(work)}>分配角色</Button></Security>
				</Space>
			)
		}
	];
}
// @ts-ignore
export default function WorkDrawer({open,onClose,user}) {
	const [list,setList] = useState<Work[]>([]);
	const corpList = useRef()
	useEffect(() => {
		loadPage(user.id);
		postFetch(apis.corpListApi, {}).then(list => {
			// @ts-ignore
			corpList.current = list;
		})
	},[user.id])
	const loadPage = (userid:string) => {
		loadWorkPage(userid).then(works => {
			// @ts-ignore
			setList(works);
		})
	}
	
	const [select,setSelect] = useState(new Work())
	const [modalStatus,setModalStatus] =
		useState({add:false,edit:false,delete:false,setRoles:false})
	const roleGroups = useRef()
	function showEditModal(work:Work) {
		setSelect({...work});
		modalStatus.edit = true;
		setModalStatus({...modalStatus})
	}
	function showDeleteModal(work:Work){
		setSelect({...work});
		modalStatus.delete = true;
		setModalStatus({...modalStatus})
	}
	function showSetRoles(work:Work){
		getFetch(apis.listRoleGroupsApi,null).then(list => {
			// @ts-ignore
			roleGroups.current = list;
			setSelect({...work});
			modalStatus.setRoles = true;
			setModalStatus({...modalStatus})
		})
	}
	function showAddModal(){
		modalStatus.add = true;
		setModalStatus({...modalStatus})
	}
	function handleEditOk(work:Work){
		modalStatus.edit = false;
		setModalStatus({...modalStatus})
		postFetch(apis.workUpdateApi,{...work,userid:user.id,id:select.id}).then(data => {
			message.success("操作成功")
			loadPage(user.id);
		})
	}
	function handleEditCancel(){
		modalStatus.edit = false;
		setModalStatus({...modalStatus})
	}
	function handleDeleteOk(work:Work){
		modalStatus.delete = false;
		setModalStatus({...modalStatus})
		postFetch(apis.workDeleteApi,{id:work.id}).then(data => {
			message.success("操作成功")
			loadPage(user.id);
		})
	}
	function handleDeleteCancel(){
		modalStatus.delete = false;
		setModalStatus({...modalStatus})
	}
	function handleAddOk(work:Work){
		modalStatus.add = false;
		setModalStatus({...modalStatus})
		postFetch(apis.workAddApi,{...work,userid:user.id}).then(data => {
			message.success("操作成功")
			loadPage(user.id);
		})
	}
	function handleAddCancel(){
		modalStatus.add = false;
		setModalStatus({...modalStatus})
	}
	function handleSetRolesOk(roleIds:any[]){
		modalStatus.setRoles = false;
		setModalStatus({...modalStatus})
		postFetch(apis.workSetRoles,{workId:select.id,roleIds:roleIds}).then(data => {
			message.success("操作成功")
			loadPage(user.id)
		})
	}
	function handleSetRolesCancel(){
		modalStatus.setRoles = false;
		setModalStatus({...modalStatus})
	}
	return (<>
			<Drawer
				title={"工作列表("+user.nickname+")"}
				width={720}
				onClose={onClose}
				open={open}
				destroyOnClose >
				<div>
					<Security perm={apis.workAddApi}><Button type="primary" onClick={showAddModal} size={"small"}>
						添加
					</Button></Security>
				</div>
				<Table columns={getColumns(showEditModal, showDeleteModal, showSetRoles)}
							 dataSource={addKey(list, user)} size={styleSize} pagination={false}
				/>
				{!modalStatus.edit && select ?<></>: <WorkEditModal open={true} onEditOk={handleEditOk} onCancel={handleEditCancel} work={select} corpList={corpList.current}/>}
				{!modalStatus.add ?<></>: <WorkAddModal open={true} onAddOk={handleAddOk} onCancel={handleAddCancel} corpList={corpList.current}/>}
				{!modalStatus.delete && select ?<></>: <WorkDeleteModal open={true} onDeleteOk={handleDeleteOk} onCancel={handleDeleteCancel} work={select}/>}
				{!modalStatus.setRoles && select ?<></>: <WorkSetRolesModal open={true} onCancel={handleSetRolesCancel} onSetRolesOk={handleSetRolesOk} work={select} roleGroups={roleGroups.current}/>}
			</Drawer>
		</>
	);
}